<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <el-date-picker disabled :type="type" :start-placeholder="placeholder[0]" :end-placeholder="placeholder[1]" size="default"/>
      <div v-if="showLength" class="length">
        <span>时长：</span>
        <span>{{ timeLength() }}</span>
      </div>
    </div>
    <div v-else-if="mode === 'PC' && !readonly">
      <el-date-picker v-model="_value" clearable :value-format="format" :format="format" :type="type" :start-placeholder="placeholder[0]" :end-placeholder="placeholder[1]" size="default"/>
      <div v-if="showLength" class="length">
        <span>时长：</span>
        <span>{{ timeLength() }}</span>
      </div>
    </div>
    <div v-else-if="mode === 'MOBILE' && !readonly">
      <field right-icon="arrow" readonly clickable name="datetimePicker" v-model="_value[0]" :placeholder="placeholder[0]" @click="loadTime(0)"/>
      <field right-icon="arrow" readonly clickable name="datetimePicker" v-model="_value[1]" :placeholder="placeholder[1]" @click="loadTime(1)"/>
      <div v-if="showLength" class="length">
        <span>时长：</span>
        <span>{{ timeLength() }}</span>
      </div>
      <popup v-model:show="showPicker" position="bottom" >
        <picker-group :title="desc" :tabs="['选择日期', '选择时间']" @confirm="onConfirm">
          <date-picker :formatter="formatter" v-model="currentDate"/>
          <time-picker v-if="format.indexOf('HH') > 0" :formatter="formatter" v-model="currentTime" />
        </picker-group>
      </popup>
    </div>
    <div v-else>{{ _value[0] }} ~ {{ _value[1] }}</div>
  </div>
</template>

<script>
import componentMinxins from '/@/views/setting/workflow/components/ComponentMinxins'
import moment from 'moment'
import {DatePicker, Field, PickerGroup, Popup, showFailToast, TimePicker} from 'vant'
import { computed, reactive, toRefs } from 'vue'
import { isNotEmpty } from '/@/utils/utils'

export default {
    name: 'DateTimeRange',
    mixins: [componentMinxins],
    components: {DatePicker, TimePicker, PickerGroup, Field, Popup },
    props: {
        modelValue: {
            type: Array,
            default: () => {
                return []
            },
        },
        format: {
            type: String,
            default: 'YYYY-MM-DD HH:mm',
        },
        placeholder: {
            type: Array,
            default: () => {
                return ['开始时间', '结束时间']
            },
        },
        showLength: {
            type: Boolean,
            default: false,
        },
    },
    emits: ['update:modelValue'],
    setup(props) {
        const { format, modelValue } = toRefs(props)
        const state = reactive({
            showPicker: false,
            valIndex: 0,
            currentDate: [],
            currentTime: [],
            timeVal: [new Date(), new Date()],
        })
        const type = computed(() => {
            switch (format.value) {
                case 'YYYY-MM-DD':
                    return 'daterange'
                case 'YYYY-MM-DD HH:mm':
                    return 'datetimerange'
                default:
                    return 'daterange'
            }
        })
        const desc = computed(() => {
            switch (format.value) {
                case 'YYYY':
                    return '选择年份'
                case 'YYYY-MM':
                    return '选择年-月'
                case 'YYYY-MM-DD':
                    return '选择年-月-日'
                case 'YYYY-MM-DD HH:mm':
                    return '选择年-月-日 时:分'
                default:
                    return '选择年-月-日 时:分'
            }
        })
        const loadTime = (index) => {
            state.showPicker = true
            state.valIndex = index
            if (isNotEmpty(modelValue.value[index])) {
                const time = modelValue.value[index].split(' ')
                state.currentDate = time[0].split('-')
                state.currentTime = time[1].split(':')
            }else {
                state.currentDate = []
                state.currentTime = []
            }
        }
        const getFormatVal = (val) => {
            return `${val[0].selectedValues.join('-')} ${val[1].selectedValues.join(':')}`
        }
        const timeLength = () => {
            //求时长算法
            if (Array.isArray(modelValue.value) && modelValue.value.length > 0) {
                let start = moment(modelValue.value[0]).format(format.value.replaceAll('dd', 'DD'))
                let end = moment(modelValue.value[1]).format(format.value.replaceAll('dd', 'DD'))
                if (start === end || modelValue.value[0] === modelValue.value[1]) {
                    return '0 （时长为0，请确认）'
                }
                let mstart = moment(start)
                let mend = moment(end)
                let years = mend.diff(start, 'years')
                let months = mend.diff(start, 'months')
                let days = mend.diff(start, 'days')
                let hours = mend.diff(start, 'hours')
                let minutes = mend.diff(start, 'minutes')
                minutes = minutes % 60
                hours = hours % 24
                months = months % 12
                //因为每月天不固定，所以天要特殊动态处理
                if (mstart.date() < mend.date()) {
                    days = mend.date() - mstart.date()
                    if (minutes > 0 || hours > 0) {
                        days--
                    }
                } else if (mstart.date() === mend.date()) {
                    //日且开始时间大于结束时间的话，日要归零
                    const s = moment(moment(start).format('HH:mm:ss'))
                    const e = moment(moment(end).format('HH:mm:ss'))
                    if (e.isBefore(s) || s._i === e._i) {
                        days = 0
                    }
                }
                //处理超过俩月且天超过31
                if (days > 31 && mend.month() - mstart.month() >= 2) {
                    //将日期推至上月求差
                    days = mend.diff(
                        mstart.add(mend.month() - mstart.month() - 1, 'month'),
                        'days'
                    )
                }
                return `${years > 0 ? years + '年 ' : ' '}${
                    months > 0 ? months + '个月 ' : ' '
                }
                        ${days > 0 ? days + '天 ' : ' '}${
                    hours > 0 ? hours + '小时 ' : ' '
                }
                    ${minutes > 0 ? minutes + '分钟 ' : ' '}`
            } else {
                return '先选择时间哦'
            }
        }
        const onConfirm = (val) => {
            state.showPicker = false
            _value.value[state.valIndex] = getFormatVal(val)
            if (_value.value[0] && _value.value[1]) {
                if (!moment(_value.value[0]).isBefore(moment(_value.value[1]))) {
                    _value.value[state.valIndex] = undefined
                    showFailToast('开始时间必须小于结束时间')
                } else {
                    context.emit('update:modelValue', _value.value)
                }
            }
        }
        const formatter = (type, option) => {
            switch (type){
                case 'year': option.text += ' 年'; break;
                case 'month': option.text += ' 月'; break;
                case 'day': option.text += ' 日'; break;
                case 'hour': option.text += ' 时'; break;
                case 'minute': option.text += ' 分'; break;
            }
            return option
        }
        return {
            ...toRefs(state),
            type,
            desc,
            loadTime,
            getFormatVal,
            timeLength,
            onConfirm,
            formatter
        }
    }
}
</script>

<style lang="scss" scoped> 
:deep(.el-date-editor .el-range-input){
    height: unset;
}
</style>